package com.tfleo.mealssenger;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Toast;

import com.github.ignition.core.widgets.RemoteImageView;
import com.tfleo.mealssenger.adapter.NewsListAdapter;
import com.tfleo.mealssenger.item.FoodItem;
import com.tfleo.mealssenger.item.Item;
import com.tfleo.mealssenger.item.PlaceItem;
import com.tfleo.mealssenger.item.SectionItem;
import com.tfleo.mealssenger.object.Place;
import com.tfleo.mealssenger.utility.DataFetcher;
import com.tfleo.mealssenger.R;

public class SearchActivity extends Activity {
	private ListView listView;
	ArrayList<Item> items = new ArrayList<Item>();
	private Context mContext;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	    setContentView(R.layout.search_layout);
	    mContext = this;

	    // Get the intent, verify the action and get the query
	    handleIntent(getIntent());
	}
	
	@Override
	protected void onNewIntent(Intent intent) {
	    setIntent(intent);
	    handleIntent(intent);
	}
	
	private void handleIntent(Intent intent){
		if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
			String query = intent.getStringExtra(SearchManager.QUERY);
		    SearchTask task = new SearchTask();
		    task.execute(query);
		}
	}

	private boolean doMySearch(String query) {
		try {
			URL url = new URL(Main.SERVER_URL + "search.php?query=" + query);
			URLConnection tc = url.openConnection();
			tc.setUseCaches(true);
			BufferedReader in = new BufferedReader(new InputStreamReader(tc.getInputStream()));

			String line;
			while ((line = in.readLine()) != null) {
				JSONObject jo = new JSONObject(line);
				if(jo.getInt("code") == 1) {
					JSONObject jresp = jo.getJSONObject("response");
					JSONArray ja1 = jresp.getJSONArray("place");
					
					items.add(new SectionItem("Places"));
					for (int i = 0; i < ja1.length(); i++) {
						JSONObject jplace= (JSONObject) ja1.get(i);

						items.add(new PlaceItem(jplace.getInt("id"),
								jplace.getString("name"),
								jplace.getString("address")));
		
					}
					items.add(new SectionItem("Foods"));
					JSONArray ja2 = jresp.getJSONArray("food");
					for (int i = 0; i < ja2.length(); i++) {
						JSONObject jfood= (JSONObject) ja2.get(i);

						items.add(new FoodItem(jfood.getInt("id"),
								jfood.getString("name"),
								jfood.getString("location"),
								jfood.getString("image")));
		
					}
					return true;
				}
				
			}
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } 
		return false;
        
        
	}
	
	
	private class SearchTask extends AsyncTask<String, Void, Boolean> {
		private ProgressDialog mProgressDialog;
		@Override    
	    protected void onPreExecute() {       
	        super.onPreExecute();
	        mProgressDialog = new ProgressDialog(mContext);
	        mProgressDialog.setMessage("Searching...");
	        mProgressDialog.setCancelable(false);
	        mProgressDialog.setIndeterminate(true);
	        mProgressDialog.show();
	    }
		
		@Override
		protected Boolean doInBackground(String... query) {
			return doMySearch(query[0]);
		}
		
		@Override
		protected void onPostExecute(Boolean result) {
			if(result) {
				EntryAdapter adapter = new EntryAdapter(mContext, items);
		        listView = (ListView) findViewById(R.id.search_result_list);
		        listView.setAdapter(adapter);
		        
		        listView.setOnItemClickListener(new OnItemClickListener() {
		        	public void onItemClick(AdapterView<?> parent, View view, int position, long id) { 
		        		Intent i;
		        		switch(items.get(position).getType()) {
		        		case SECTION:
		        			break;
		        		case FOOD:
		        			i = new Intent(mContext,
		    						FoodActivity.class);

		    				FoodItem foodItem = (FoodItem) items.get(position);
		    				i.putExtra("id", foodItem.foodName);
		    				startActivity(i);
		        			break;
		        		case PLACE:
		        			i = new Intent(mContext,
		    						PlaceActivity.class);

		    				PlaceItem placeItem = (PlaceItem) items.get(position);
		    				i.putExtra("id", placeItem.placeName);
		    				startActivity(i);
		        		}
		        			
		        	}
		        });
    		} else {
    			Toast.makeText(mContext, "Error: Connection with server failed!", Toast.LENGTH_SHORT).show();
    		}
			mProgressDialog.dismiss();
	    }
		
	}
	
	public class EntryAdapter extends ArrayAdapter<Item> {
		private ArrayList<Item> items;
		private LayoutInflater vi;

		public EntryAdapter(Context context, ArrayList<Item> items) {
			super(context, 0, items);
			this.items = items;
			vi = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View v = convertView;

			final Item i = (Item) items.get(position);
			if (i != null) {
				switch(i.getType()) {
					case SECTION:
						SectionItem si = (SectionItem)i;
						v = vi.inflate(R.layout.search_section, null);
	
						v.setOnClickListener(null);
						v.setOnLongClickListener(null);
						v.setLongClickable(false);
	
						final TextView sectionView = (TextView) v.findViewById(R.id.search_section_text);
						sectionView.setText(si.getTitle());
						break;
					
					case FOOD:
						FoodItem fi = (FoodItem)i;
						v = vi.inflate(R.layout.search_result_food_entry, null);
						final TextView foodNameView = (TextView)v.findViewById(R.id.name);
						final TextView foodWhereView = (TextView)v.findViewById(R.id.where);
						final RemoteImageView foodImageView = (RemoteImageView) v.findViewById(R.id.img);
						

						if(foodNameView != null)
							foodNameView.setText(fi.foodName);
						if(foodWhereView != null)
							foodWhereView.setText(fi.foodWhere);
						if(foodImageView != null) {
							foodImageView.setImageUrl(fi.foodImage);
							foodImageView.loadImage();
						}
						break;
					
					case PLACE:
						PlaceItem pi = (PlaceItem)i;
						v = vi.inflate(R.layout.search_result_place_entry, null);
						final TextView placeNameView = (TextView)v.findViewById(R.id.name);
						final TextView placeAddressView = (TextView)v.findViewById(R.id.where);
						

						if(placeNameView != null)
							placeNameView.setText(pi.placeName);
						if(placeAddressView != null)
							placeAddressView.setText(pi.placeAddress);	
						break;
						
				
				}
				
			}
			return v;
		}
	}
}
